import React, { useEffect, useState } from 'react';
import { Card, Button, Popconfirm, Table, message } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { getCategory } from '../../services/category';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { request } from '@umijs/max';
import Dialog from './components/Dialog';
import { history, useLocation } from '@umijs/max';

type Category = {
  categoryId: number;
  categoryLevel: number;
  parentId: number;
  categoryName: string;
  categoryRank: number;
  isDeleted: 0 | 1;
  createTime: string;
  createUser: number;
  updateTime: string;
  updateUser: number;
};

const CategoryAdmin = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalShow, setModalShow] = useState(false);
  const [modalType, setModalType] = useState<'edit' | 'add'>('edit');
  const [category, setCategory] = useState<Partial<Category>>({});
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [level, setLevel] = useState(1);
  const [parentId, setParentId] = useState(0);

  const location = useLocation();

  useEffect(() => {
    const query = new URLSearchParams(location.search);
    // 通过 get 方法获取具体的查询参数值
    const level = Number(query.get('level')) || 1;
    const parent_id = Number(query.get('parent_id')) || 0;
    setLevel(level);
    setParentId(parent_id);
  }, [location.search]);

  const fetchData = () => {
    setLoading(true);
    getCategory({
      pageNumber: pagination.current as number,
      pageSize: pagination.pageSize as number,
      categoryLevel: level,
      parentId,
    }).then((res) => {
      setCategories(res.data?.list || []);
      setPagination({
        ...pagination,
        total: res.data?.totalCount,
      });
      setLoading(false);
    });
  };

  useEffect(() => {
    fetchData();
  }, [JSON.stringify(pagination), level, parentId]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  // 下级分类
  const handleNext = (item: Category) => {
    const levelNumber = item.categoryLevel + 1;
    if (levelNumber >= 4) {
      message.error('没有下一级，最高支持3级分类');
      return;
    }
    history.push(`/admin/category?level=${levelNumber}&parent_id=${item.categoryId}`);
  };

  // 添加分类
  const handleAdd = () => {
    setModalType('add');
    setModalShow(true);
    setCategory({});
  };

  // 编辑分类
  const handleEdit = (category: Category) => {
    setModalType('edit');
    setModalShow(true);
    setCategory(category);
  };

  // 删除分类
  const handleDelete = () => {
    if (!selectedRowKeys.length) {
      message.error('请选择项');
      return;
    }
    request('/categories', {
      method: 'delete',
      data: {
        ids: selectedRowKeys,
      },
      headers: {
        token: localStorage.getItem('token') || '',
      },
    }).then(() => {
      message.success('删除成功');
      fetchData();
    });
  };

  // 删除单个分类
  const handleDeleteOne = (id: number) => {
    request('/categories', {
      method: 'delete',
      data: {
        ids: [id],
      },
      headers: {
        token: localStorage.getItem('token') || '',
      },
    }).then(() => {
      message.success('删除成功');
      fetchData();
    });
  };

  const columns: ColumnsType<Category> = [
    {
      title: '分类名称',
      dataIndex: 'categoryName',
    },
    {
      title: '排序值',
      dataIndex: 'categoryRank',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render: (_: any, item: Category) => {
        return (
          <>
            <a style={{ cursor: 'pointer', marginRight: '10px' }} onClick={() => handleEdit(item)}>
              编辑
            </a>
            <a style={{ cursor: 'pointer', marginRight: '10px' }} onClick={() => handleNext(item)}>
              下级分类
            </a>
            <Popconfirm
              title="确定删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => handleDeleteOne(item.categoryId)}
            >
              <a style={{ cursor: 'pointer', color: 'red' }}>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  return (
    <>
      <Card>
        <div style={{ marginRight: '10px', marginBottom: '10px' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
            style={{ marginRight: 10 }}
          >
            增加
          </Button>
          <Popconfirm
            title="确定删除吗？"
            confirmButtonText="确定"
            cancelButtonText="取消"
            onConfirm={handleDelete}
          >
            <Button danger icon={<DeleteOutlined />}>
              批量删除
            </Button>
          </Popconfirm>
        </div>
        <Table
          loading={loading}
          columns={columns}
          dataSource={categories}
          rowKey="categoryId"
          pagination={{
            ...pagination,
            onChange: (page, pageSize) => {
              setPagination({
                ...pagination,
                current: page,
                pageSize,
              });
            },
          }}
          rowSelection={rowSelection}
        />
      </Card>

      {modalShow && (
        <Dialog
          type={modalType}
          visible={modalShow}
          defaultCategory={category}
          onClose={() => {
            setModalShow(false);
            fetchData();
          }}
        />
      )}
    </>
  );
};

export default CategoryAdmin;
